package fu.k4c.vTeam.Route;

import java.text.DecimalFormat;
import java.util.Timer;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;

import fu.k4c.vTeam.R;
import fu.k4c.vTeam.Controller.VlocationItemizedOverlay;
import fu.k4c.vTeam.Object.MyLocation;
import fu.k4c.vTeam.Object.MyLocation.LocationResult;

public class RouterActivity extends MapActivity {
	VlocationItemizedOverlay mMyOverlay1, mMyOverlay2;
	int slat, slong;
	ProgressDialog proDialog;
	LocationManager mLocationManager;
	LocationListener mLocationListener;
	MapView mapView;
	Timer timer1;
	LocationManager lm;
	LocationResult locationResult;
	boolean gps_enabled = false;
	boolean network_enabled = false;
	LocationListener locationListenerGps;
	LocationListener locationListenerNetwork;
	int i = 1;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.route);

		mapView = (MapView) findViewById(R.id.map_route);
		mapView.setBuiltInZoomControls(true);
		Bundle data = getIntent().getExtras();
		try {
			if (data != null) {
				slat = data.getInt("lat");
				slong = data.getInt("long");
			}
			mapView.getController().setZoom(15);
			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
					.permitAll().build();
			StrictMode.setThreadPolicy(policy);
			proDialog = ProgressDialog.show(RouterActivity.this, "",
					"Đang xác định địa điểm hiện tại ...");
			new Thread() {
				public void run() {

					try {
						sleep(1500);
					} catch (Exception e) {
						System.out.print(e.toString());
					}
					// dismiss the progressdialog
					proDialog.dismiss();
				}
			}.start();
			final LocationResult locationResult = new LocationResult() {
				@Override
				public void gotLocation(Location location) {
					// Got the location!
					final Location lol = location;
					if (location != null) {
						runOnUiThread(new Runnable() {
							public void run() {
						GeoPoint p1 = new GeoPoint(
								(int) (lol.getLatitude() * 1e6),
								(int) (lol.getLongitude() * 1e6));
						GeoPoint p2 = new GeoPoint(slat, slong);
						float distance = distFrom(
								(int) (lol.getLatitude() * 1e6),
								(int) (lol.getLongitude() * 1e6), slat,
								slong);
						DecimalFormat df = new DecimalFormat("0.0");
						String str = df.format(distance / 1000000);
						if(i==1)
						{
							Toast.makeText(getApplicationContext(),
									"Khoảng cách " + str + " km", Toast.LENGTH_LONG)
									.show();
							i++;
						}
						
						mMyOverlay1 = new VlocationItemizedOverlay(
								getResources().getDrawable(R.drawable.point1));
						OverlayItem newplace1 = new OverlayItem(p1,
								"New Place", "New Location");
						mMyOverlay1.addOverlay(newplace1);
						mMyOverlay2 = new VlocationItemizedOverlay(
								getResources().getDrawable(R.drawable.point2));
						OverlayItem newplace2 = new OverlayItem(p2,
								"New Place", "New Location");
						mMyOverlay2.addOverlay(newplace2);
						mapView.getOverlays().add(mMyOverlay1);
						mapView.getOverlays().add(mMyOverlay2);
						mapView.invalidate();
						mapView.getController().animateTo(p1);
						Route route = directions(p1, p2);
						RouteOverlay routeOverlay = new RouteOverlay(route,
								Color.BLUE);
						mapView.getOverlays().add(routeOverlay);
							}
						});
					} else {
						runOnUiThread(new Runnable() {
							public void run() {
								Toast.makeText(getApplicationContext(),
										"Không xác định được địa điểm",
										Toast.LENGTH_LONG).show();
								finish();
							}
						});
					}

				}
			};
			MyLocation myLocation = new MyLocation();
			myLocation.getLocation(this, locationResult);

			Button back = (Button) findViewById(R.id.btn_route_back);
			back.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					// TODO Auto-generated method stub
					finish();
				}
			});

			locationListenerNetwork = new LocationListener() {
				public void onLocationChanged(Location location) {
					try {
						mapView.getOverlays().clear();
						mapView.invalidate();
					} catch (Exception e) {
						// TODO: handle exception
					}
					GeoPoint p1 = new GeoPoint(
							(int) (location.getLatitude() * 1e6),
							(int) (location.getLongitude() * 1e6));
					GeoPoint p2 = new GeoPoint(slat, slong);
					mMyOverlay1 = new VlocationItemizedOverlay(getResources()
							.getDrawable(R.drawable.point1));
					OverlayItem newplace1 = new OverlayItem(p1, "New Place",
							"New Location");
					mMyOverlay1.addOverlay(newplace1);
					mMyOverlay2 = new VlocationItemizedOverlay(getResources()
							.getDrawable(R.drawable.point2));
					OverlayItem newplace2 = new OverlayItem(p2, "New Place",
							"New Location");
					mMyOverlay2.addOverlay(newplace2);
					mapView.getOverlays().add(mMyOverlay1);
					mapView.getOverlays().add(mMyOverlay2);
					mapView.invalidate();
					mapView.getController().animateTo(p1);
					Route route = directions(p1, p2);
					RouteOverlay routeOverlay = new RouteOverlay(route,
							Color.BLUE);
					mapView.getOverlays().add(routeOverlay);
				}

				public void onProviderDisabled(String provider) {
				}

				public void onProviderEnabled(String provider) {
				}

				public void onStatusChanged(String provider, int status,
						Bundle extras) {
				}
			};
			locationListenerGps = new LocationListener() {
				public void onLocationChanged(Location location) {
					try {
						mapView.getOverlays().clear();
						mapView.invalidate();
					} catch (Exception e) {
						// TODO: handle exception
					}
					GeoPoint p1 = new GeoPoint(
							(int) (location.getLatitude() * 1e6),
							(int) (location.getLongitude() * 1e6));
					GeoPoint p2 = new GeoPoint(slat, slong);
					mMyOverlay1 = new VlocationItemizedOverlay(getResources()
							.getDrawable(R.drawable.point1));
					OverlayItem newplace1 = new OverlayItem(p1, "New Place",
							"New Location");
					mMyOverlay1.addOverlay(newplace1);
					mMyOverlay2 = new VlocationItemizedOverlay(getResources()
							.getDrawable(R.drawable.point2));
					OverlayItem newplace2 = new OverlayItem(p2, "New Place",
							"New Location");
					mMyOverlay2.addOverlay(newplace2);
					mapView.getOverlays().add(mMyOverlay1);
					mapView.getOverlays().add(mMyOverlay2);
					mapView.invalidate();
					mapView.getController().animateTo(p1);
					Route route = directions(p1, p2);
					RouteOverlay routeOverlay = new RouteOverlay(route,
							Color.BLUE);
					mapView.getOverlays().add(routeOverlay);
				}

				public void onProviderDisabled(String provider) {
				}

				public void onProviderEnabled(String provider) {
				}

				public void onStatusChanged(String provider, int status,
						Bundle extras) {
				}
			};
			if (lm == null)
				lm = (LocationManager) this
						.getSystemService(Context.LOCATION_SERVICE);

			// exceptions will be thrown if provider is not permitted.
			try {
				gps_enabled = lm
						.isProviderEnabled(LocationManager.GPS_PROVIDER);
			} catch (Exception ex) {
			}
			try {
				network_enabled = lm
						.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
			} catch (Exception ex) {
			}
			if (gps_enabled)
				lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
						locationListenerGps);
			if (network_enabled)
				lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0,
						0, locationListenerNetwork);

		} catch (Exception e) {
			// TODO: handle exception
			Toast.makeText(getApplicationContext(),
					"Không xác định được địa điểm", Toast.LENGTH_LONG).show();
		}
	}

	private Route directions(final GeoPoint start, final GeoPoint dest) {
		Parser parser;
		String jsonURL = "http://maps.google.com/maps/api/directions/json?";
		final StringBuffer sBuf = new StringBuffer(jsonURL);
		sBuf.append("origin=");
		sBuf.append(start.getLatitudeE6() / 1E6);
		sBuf.append(',');
		sBuf.append(start.getLongitudeE6() / 1E6);
		sBuf.append("&destination=");
		sBuf.append(dest.getLatitudeE6() / 1E6);
		sBuf.append(',');
		sBuf.append(dest.getLongitudeE6() / 1E6);
		sBuf.append("&sensor=true&mode=driving");
		parser = new GoogleParser(sBuf.toString());
		Route r = parser.parse();
		return r;
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	public static float distFrom(float lat1, float lng1, float lat2, float lng2) {
		double earthRadius = 3958.75;
		double dLat = Math.toRadians(lat2 - lat1);
		double dLng = Math.toRadians(lng2 - lng1);
		double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
				+ Math.cos(Math.toRadians(lat1))
				* Math.cos(Math.toRadians(lat2)) * Math.sin(dLng / 2)
				* Math.sin(dLng / 2);
		double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
		double dist = earthRadius * c;

		int meterConversion = 1609;

		return new Float(dist * meterConversion).floatValue();
	}
}
